package com.data.hijack.service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

import org.apache.log4j.Logger;

import com.data.hijack.util.AppUtils;
import com.data.hijack.util.BeanUtils;

/**
 * @author husq
 */
public class Service extends Thread {
    private static final Logger logger = Logger.getLogger(Service.class);

    private String host;
    private int port;
    private String bizName;

    public Service(String host, int port, String bizName) {
        this.host = host;
        this.port = port;
        this.bizName = bizName;
    }

    @Override
    public void run() {
        ServerSocketChannel serverSocketChannel = null;
        Selector selector = null;
        try {
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(host, port));
            selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT,
                BeanUtils.instantiateClass(
                    ReceivedHandler.class.getDeclaredConstructor(ServerSocketChannel.class, String.class),
                    new Object[] {serverSocketChannel, bizName}));
            while (true) {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    Dispatcher.dispatch(selectionKey);
                }
            }
        } catch (IOException e) {
            logger.error(e);
        } catch (Exception e) {
            logger.error(e);
        } finally {
            AppUtils.closeChannel(serverSocketChannel, selector);
        }
    }
}
